package com.lmx.persistence.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lmx.common.constants.CommonConstants;
import com.lmx.common.context.ActionContextHolder;
import com.lmx.common.util.CommonUtil;
import com.lmx.repoDomain.tmodel.Customer;
import com.lmx.repoDomain.tmodel.Department;
import com.lmx.repoDomain.tmodel.Dicttype;
import com.lmx.repoDomain.tmodel.Employee;
import com.lmx.repoDomain.tmodel.NurseGroup;
import com.lmx.repoDomain.tmodel.Role;//huibati
import com.lmx.repoDomain.tmodel.Tenant;
//import com.lmx.repoDomain.model.*;
import com.lmx.repoDomain.tmodel.business.User;//huibati

/**
 * #{description}
 *
 * @author Administrator
 * @version 1.00
 */
@Service
@Scope("prototype")
public class UserService<T> {
	private Log logger = LogFactory.getLog(this.getClass());

	@PersistenceContext
	private EntityManager em;

	@Autowired
	protected GenericService dslJpaService;

	@Autowired
	protected CommonService commonService;

	/**
	 * 获取用户列表总条数
	 *
	 * @param values
	 * @return
	 */
	public int getUserListCount(Map<String, Object> values) {

		logger.debug("获取用户列表总条数");

		String query = "select count(u.id) from User u , Role r where u.role.id = r.id and u.delStatus != '1'";

		String roleCode = (String) values.get("roleCode");
		if (roleCode != null && !roleCode.isEmpty()) {
			query = query + " and r.code in (" + roleCode + ")";
		}

		String loginName = (String) values.get("loginName");
		if (loginName != null && !loginName.isEmpty()) {
			query = query + " and u.loginName like '%" + loginName + "%'";
		}

		String entName = (String) values.get("entName");
		if (entName != null && !entName.isEmpty()) {
			query = query + " and u.entName like '%" + entName + "%'";
		}
		String name = (String) values.get("name");
		if (name != null && !name.isEmpty()) {
			query = query + " and u.name like '%" + name + "%'";
		}
		String phone = (String) values.get("phone");
		if (phone != null && !phone.isEmpty()) {
			query = query + " and u.phone like '%" + phone + "%'";
		}
		String status = (String) values.get("status");
		if (status != null && !status.isEmpty()) {
			query = query + " and u.status = " + status;
		}

		int count = (int) (long) this.em.createQuery(query).getSingleResult();

		return count;
	}

	/**
	 * 修改用户状态
	 *
	 * @param user
	 * @return
	 */
	@Transactional
	public void updateUserStatus(User user) {

		logger.debug("修改用户状态");

		String query = "update User u set u.status = ?1 , u.updateTime = ?3 where u.id = ?2";

		String verifyFailReason = user.getVerifyFailReason();
		if (verifyFailReason != null && !verifyFailReason.isEmpty()) {
			query = "update User u set u.status = ?1 , u.updateTime = ?3 , u.verifyFailReason = '"
					+ verifyFailReason + "' where u.id = ?2";
		}

		// 修改用户状态
		this.em.createQuery(query).setParameter(1, user.getStatus()).setParameter(2, user.getId())
				.setParameter(3, CommonUtil.getCurrTimes()).executeUpdate();
	}

	/*
	 * 获得某租户下所有工作人员用户
	 * 
	 * @params tenant 对应租户
	 */
	public List<User> getAllUserList(Tenant tenant) {
		// 注意需要清除掉对应的公众号用户
		StringBuilder query = new StringBuilder("select u from User u inner join u.role as role "
				+ "where u.tenant.id = " + tenant.getId()
				+ " and u.delStatus!=1 and ( role.code!='wechat' or role.code is null )");
		List<User> userList = this.em.createQuery(query.toString()).getResultList();
		return userList;
	}

	/**
	 * 获取
	 */
	public User getUsersByLoginName(User user) {
		Long t = ActionContextHolder.getContext().getTenantId();
		StringBuilder query = new StringBuilder(
				"select c from User c where  c.tenant.id=?1  and c.loginName=?2  and c.delStatus != ?3 ");
		List resultList = this.em.createQuery(query.toString())
				.setParameter(1, ActionContextHolder.getContext().getTenantId())
				.setParameter(2, user.getLoginName()).setParameter(3, (short) 1).getResultList();
		User u = null;
		if (resultList.size() > 0) {
			u = (User) resultList.get(0);
		}
		return u;
	}

	/**
	 * 获取
	 */
	public User getUsersByCardCode(User user) {
		StringBuilder query = new StringBuilder(
				"select c from User c where  c.tenant.id=?1 and c.staffCardCode=?2 and c.delStatus != ?3 ");
		List resultList = this.em.createQuery(query.toString())
				.setParameter(1, ActionContextHolder.getContext().getTenantId())
				.setParameter(2, user.getStaffCardCode()).setParameter(3, (short) 1)
				.getResultList();
		User u = null;
		if (resultList.size() > 0) {
			u = (User) resultList.get(0);
		}
		return u;
	}

	/**
	 * 获取
	 */
	public Role getRoleByUserId(Long userId) {
		User user = getUserById(userId);
		StringBuilder query = new StringBuilder(
				"select c from Role c where  c.tenant.id=?1 and c.id=?2 ");
		List resultList = this.em.createQuery(query.toString())
				.setParameter(1, user.getTenant().getId()).setParameter(2, user.getRole().getId())
				.getResultList();
		Role u = null;
		if (resultList.size() > 0) {
			u = (Role) resultList.get(0);
		}
		return u;
	}

	/**
	 *
	 */
	@Transactional
	public void deleteStaffCustomer(Long staffId) {
		if (staffId != null) {
			StringBuilder query = new StringBuilder(
					"delete from StaffCustomer rp where rp.staff.id = ?1");
			this.em.createQuery(query.toString()).setParameter(1, staffId).executeUpdate();
		}
	}

	/**
	 * 获取
	 */
	public User getUserByLoginName(String loginName) {
		StringBuilder query = new StringBuilder(
				"select c from User c where c.loginName = ?1  and c.tenant.id=?2 ");
		List dataList = this.em.createQuery(query.toString()).setParameter(1, loginName)
				.setParameter(2, ActionContextHolder.getContext().getTenantId()).getResultList();
		User ct = null;
		if (dataList.size() > 0) {
			ct = (User) dataList.get(0);
		}
		return ct;
	}

	/**
	 * 获取
	 */
	public List getEmployeeByGroup(NurseGroup group) {
		Long groupId = group.getId();
		StringBuilder query = new StringBuilder(
				"select c from Employee c where c.delStatus != ?2 and c.nurseGroup.id = ?1 ");
		List resultList = this.em.createQuery(query.toString()).setParameter(1, groupId)
				.setParameter(2, (short) 1).getResultList();

		return resultList;
	}

	/**
	 * 获取
	 */
	public User getUserById(Long id) {
		List dataList = new ArrayList<>();
		StringBuilder query = new StringBuilder("select c from User c where c.id = ?1");
		try {
			dataList = this.em.createQuery(query.toString()).setParameter(1, id).getResultList();
		} catch (Exception e) {
			logger.debug("getUserById  error " + e);
		}
		User ct = null;
		if (dataList.size() > 0) {
			ct = (User) dataList.get(0);
		}
		return ct;
	}

	/**
	 * 获取
	 */
	public Department getDepartmentById(Long id) {
		StringBuilder query = new StringBuilder(
				"select c from Department c where c.id = ?1 and  c.delStatus != ?2 ");
		List dataList = this.em.createQuery(query.toString()).setParameter(1, id)
				.setParameter(2, (short) 1).getResultList();
		Department ct = null;
		if (dataList.size() > 0) {
			ct = (Department) dataList.get(0);
		}
		return ct;
	}

	/**
	 * 获取
	 */
	public Department getDepartmentByName(String name) {
		StringBuilder query = new StringBuilder(
				"select c from Department c where c.name = ?1 and  c.delStatus != ?2 and c.tenant.id=?3 ");
		List dataList = this.em.createQuery(query.toString()).setParameter(1, name)
				.setParameter(2, (short) 1)
				.setParameter(3, ActionContextHolder.getContext().getTenantId()).getResultList();
		Department ct = null;
		if (dataList.size() > 0) {
			ct = (Department) dataList.get(0);
		}
		return ct;
	}

	/**
	 * 获取
	 */
	public Employee getEmployeeById(Long id) {
		StringBuilder query = new StringBuilder(
				"select c from Employee c where c.delStatus != ?2 and c.id = ?1");
		List resultList = this.em.createQuery(query.toString()).setParameter(1, id)
				.setParameter(2, (short) 1).getResultList();
		Employee ct = null;
		if (resultList.size() > 0) {
			ct = (Employee) resultList.get(0);
		}
		return ct;

	}

	/**
	 * 获取
	 */
	public List getEmployeeByCardCode(String staffCardCode) {
		StringBuilder query = new StringBuilder(
				"select c from Employee c where c.delStatus != ?2 and c.staffCardCode = ?1  and c.tenant.id=?3 ");
		List resultList = this.em.createQuery(query.toString()).setParameter(1, staffCardCode)
				.setParameter(2, (short) 1)
				.setParameter(3, ActionContextHolder.getContext().getTenantId()).getResultList();
		return resultList;
	}

	/**
	 * 获取
	 */
	public List getEmployeeByCardCodeFilterId(String staffCardCode, Long staffId) {
		StringBuilder query = new StringBuilder(
				"select c from Employee c where c.delStatus != ?2 and c.staffCardCode = ?1  and c.tenant.id=?3 and c.id != ?4 ");
		List resultList = this.em.createQuery(query.toString()).setParameter(1, staffCardCode)
				.setParameter(2, (short) 1)
				.setParameter(3, ActionContextHolder.getContext().getTenantId())
				.setParameter(4, staffId).getResultList();
		return resultList;
	}

	/**
	 * 获取关注老人的user
	 */
	public List getUsersByCustomer(Customer customer) {
		StringBuilder query = new StringBuilder(
				"select c.staff from StaffCustomer c where  c.tenant.id=?1  and c.customer.id=?2  and c.delStatus != ?3 ");
		List resultList = this.em.createQuery(query.toString())
				.setParameter(1, customer.getTenant().getId()).setParameter(2, customer.getId())
				.setParameter(3, (short) 1).getResultList();

		return resultList;
	}

	public void deleteByEmployee(Employee employee) {
		Dicttype status = commonService.getDicttype(CommonConstants.DICTTYPE.EMPLOYEE_STATUS_2
				.label());
		StringBuilder query = new StringBuilder(
				"update  User u set u.staffStatus=?2 where employee= ?1");
		this.em.createQuery(query.toString()).setParameter(1, employee).setParameter(2, status)
				.executeUpdate();
	}

	/**
	 * @author ytche
	 * @param loginName
	 * @return
	 * @date 2017年5月11日 上午10:39:57
	 */
	public List<User> findUsersByLoginName(String loginName) {
		loginName = "%" + loginName + "%";
		String hql = "FROM User where loginName like :loginName";
		return this.em.createQuery(hql).setParameter("loginName", loginName).getResultList();
	}

	/**
	 * 重置密码
	 *
	 * @author ytche
	 * @param mobile
	 * @param password
	 * @date 2017年9月7日 下午3:31:52
	 */
	public void resetPassword(String mobile, String password) {
		List<User> users = this.findUsersByLoginName(mobile);
		dslJpaService.setEntityClass(User.class);
		for (User user : users) {
			user.setPasscode(password);
			this.dslJpaService.update(user);
		}
	}
}
